package com.wing.product.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.platform.feign.PlatformClient;
import com.wing.product.model.entity.ProductCategory;
import com.wing.product.model.request.ProductCategoryForm;
import com.wing.product.model.response.ProductCategoryVO;
import com.wing.product.service.ProductCategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-产品分类管理", tags = "#/product/productCategory")
@RestController("productCategoryController")
@RequestMapping("product/admin/productCategory")
public class ProductCategoryController {

    @Autowired
    private ProductCategoryService productCategoryService;
    @Autowired
    private PlatformClient platformClient;


    @ApiOperation(value = "查询所有产品分类", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "name", value = "名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<ProductCategory> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,String name
            ,@RequestParam(defaultValue = "enterprise") ProductCategory.DataSourceType dataSourceType
    ){

        Page<ProductCategory> pg = new Page<>(page, limit);
        QueryWrapper<ProductCategory> queryWrapper = new QueryWrapper<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }
        queryWrapper.eq("data_source_type", ProductCategory.DataSourceType.enterprise.getValue());

        //搜索
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        if (dataSourceType!=null){
            queryWrapper.eq("data_source_type",dataSourceType.getValue());
        }
//        queryWrapper.eq("category_type",1);
        IPage<ProductCategory> list = productCategoryService.getBaseMapper().selectPage(pg, queryWrapper);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加产品分类", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(ProductCategoryForm.Add.class) ProductCategoryForm productCategoryForm) {

        if (productCategoryService.add(productCategoryForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改产品分类", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(ProductCategoryForm.Update.class) ProductCategoryForm productCategoryForm) {

        ProductCategory productCategory = productCategoryService.getById(productCategoryForm.getId());
        if(productCategory == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(ProductCategory.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(productCategoryForm, productCategory, copyOptions);
        if (productCategoryService.update(productCategoryForm)>=0) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除产品分类", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productCategoryId", value = "产品分类id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long productCategoryId) {

        if (productCategoryService.del(productCategoryId)>=0) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }


    @ApiOperation(value = "作废产品分类", notes = "作废")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productCategoryId", value = "产品分类id", required = true, dataType = "Integer", paramType = "path")
    })
    @PostMapping("/invalid/{id}" )
    public JsonResult invalid(@PathVariable("id") Long productCategoryId) {

        if (productCategoryService.removeById(productCategoryId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }


    @ApiOperation(value = "启用产品分类", notes = "启用")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/enable")
    public JsonResult enable(@Validated(ProductCategoryForm.Add.class) ProductCategoryForm productCategoryForm) {

//        ProductCategory productCategory=new ProductCategory();
//        productCategory.setId(productCategoryForm.getId());
//        productCategory.setIsDeleted(true);
        if (productCategoryService.enable(productCategoryForm.getId())>=0) {
            return JsonResult.success("启用成功");
        }
        return JsonResult.fail("启用失败");
    }

    @ApiOperation(value = "停用产品分类", notes = "停用")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/disable")
    public JsonResult disable(@Validated(ProductCategoryForm.Add.class) ProductCategoryForm productCategoryForm) {

//        ProductCategory productCategory=new ProductCategory();
//        productCategory.setId(productCategoryForm.getId());
//        productCategory.setIsDeleted(false);
        if (productCategoryService.disable(productCategoryForm.getId())>=0) {
            return JsonResult.success("停用成功");
        }
        return JsonResult.fail("停用失败");
    }

    @ApiOperation(value = "获取所有产品分类树", notes = "添加属性")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @GetMapping("/getTreeData")
    public JsonResult getTreeData() {

        return productCategoryService.getTreeData();
    }

    @ApiOperation(value = "查询所有产品分类", notes = "查询所有产品分类")
    @GetMapping("/getAll")
    public JsonResult<ProductCategoryVO> getAll(ProductCategory.CategoryType categoryType){

        QueryWrapper<ProductCategory> wrapper = new QueryWrapper<>();
        //wrapper.select("id","name","parent_id");
        wrapper.eq("data_source_type", ProductCategory.DataSourceType.enterprise.getValue());
        if(null != categoryType){
            wrapper.eq("category_type",categoryType.getValue());
        }
        List<ProductCategory> productCategory = productCategoryService.list(wrapper);
        return JsonResult.success(productCategory);
    }

    @ApiOperation(value = "根据类型ID查询产品分类", notes = "查询产品分类")
    @GetMapping("/getProductCategoryByType")
    public JsonResult<ProductCategory> getProductCategoryByType(Integer type, ProductCategory.CategoryType categoryType){

        QueryWrapper<ProductCategory> wrapper = new QueryWrapper<>();
        if(null != type){
            wrapper.eq("type", type);
        }
        if(null != categoryType){
            wrapper.eq("category_type", categoryType.getValue());
        }
        wrapper.eq("is_deleted", 1);
        wrapper.select("id","name","parent_id","is_deleted");
        wrapper.eq("data_source_type", ProductCategory.DataSourceType.enterprise.getValue());
        List<ProductCategory> productCategory = productCategoryService.list(wrapper);
        return JsonResult.success(productCategory);
    }
    @ApiOperation(value = "查询平台的所有产品分类", notes = "查询平台的所有产品分类")
    @GetMapping("/platformProductCategoryList")
    public JsonResult platformProductCategoryList(){
        return platformClient.platformProductCategoryList();
    }

}
